/**
 * @Author: 陈瑞鹏
 * @Date:   2025-01-07 10:56:17
 * @Last Modified by:   陈瑞鹏
 * @Last Modified time: 2025-01-20 11:43:08
 */
import GameData from "./GameData";
import ReportLogs from "./ReportLogs";
import SocketManager from "./socket/SocketManager";
import { drawScroll, objSort } from "./Utils";

const { ccclass, property } = cc._decorator;
@ccclass
export default class GameMain extends cc.Component {

  @property({ type: cc.Node, tooltip: "移动节点" })
  moveNode: cc.Node = null;

  @property({ type: cc.Label, tooltip: "获得的金钱" })
  moneyTxt: cc.Label = null;

  @property({ type: cc.Label, tooltip: "倒计时时间" })
  timeTxt: cc.Label = null;

  @property({ type: cc.Prefab, tooltip: "预制体" })
  moneyPrefab: cc.Prefab = null;

  @property({ type: cc.Node, tooltip: "开始节点" })
  startNode: cc.Node = null;

  @property({ type: cc.Node, tooltip: "动画节点" })
  aniNode: cc.Node = null;

  @property({ type: cc.Node, tooltip: "结束节点" })
  endNode: cc.Node = null;

  @property({ type: cc.Label, tooltip: "结算的金钱" })
  endMoneyTxt: cc.Label = null;

  @property({ type: cc.Prefab, tooltip: "数据列表预制体" })
  itemPrefab: cc.Prefab = null;

  @property({ type: cc.Prefab, tooltip: "数据列表预制体" })
  itemPrefab2: cc.Prefab = null;

  @property({ type: cc.Node, tooltip: "列表节点" })
  listNode: cc.Node = null;

  @property({ type: cc.Node, tooltip: "列表内容" })
  listCont: cc.Node = null;

  @property({ type: cc.Node, tooltip: "准备节点" })
  readyNode: cc.Node = null;

  @property({ type: cc.Node, tooltip: "准备内容节点" })
  readyCont: cc.Node = null;

  @property({ type: cc.Node, tooltip: "准备按钮" })
  readyBtn: cc.Node = null;

  @property({ type: cc.Node, tooltip: "开始按钮" })
  startBtn: cc.Node = null;

  @property({ type: cc.Node, tooltip: "解散按钮" })
  disBtn: cc.Node = null;

  @property({ type: cc.Node, tooltip: "退出按钮" })
  leaveBtn: cc.Node = null;

  @property({ type: cc.Node, tooltip: "邀请按钮" })
  shareBtn: cc.Node = null;

  @property({ type: cc.Label, tooltip: "房间号" })
  roomIdTxt: cc.Label = null;

  @property({ type: cc.EditBox, tooltip: "输入房间号" })
  inputRoomId: cc.EditBox = null;

  @property({ type: cc.Label, tooltip: "房间总人数" })
  allNum: cc.Label = null;

  @property({ type: cc.Node, tooltip: "提示" })
  tipNode: cc.Node = null;

  @property({ type: cc.Node, tooltip: "邀请节点" })
  shareNode: cc.Node = null;

  @property({ type: cc.Label, tooltip: "房间号" })
  roomIdTxt2: cc.Label = null;

  @property({ type: cc.Node, tooltip: "准备节点" })
  rdNode: cc.Node = null;

  @property({ type: cc.Label, tooltip: "准备倒计时" })
  rdDownTxt: cc.Label = null;

  @property({ type: cc.Node, tooltip: "统计界面" })
  jsNode: cc.Node = null;

  @property({ type: cc.Label, tooltip: "结算倒计时" })
  jsTxt: cc.Label = null;

  @property({ type: cc.Label, tooltip: "我的排名" })
  myRankTxt: cc.Label = null;

  @property({ type: cc.Label, tooltip: "我的积分" })
  myScoreTxt: cc.Label = null;

  @property({ type: cc.Node, tooltip: "分页节点" })
  pageNode: cc.Node = null;

  @property({ type: cc.Label, tooltip: "分页数量节点" })
  pageNum: cc.Label = null;

  private jsTime = null;

  private jsNum = 3;

  private reconnectCount: number = 0;
  private readonly MAX_RECONNECT_COUNT: number = 3;
  private isReconnecting: boolean = false;

  protected onLoad(): void {
    // 上报日志
    ReportLogs.ins.behaviorReporting("房间操作", "游戏场景加载", GameData.ins.username);

    GameData.ins.mainNode = this.node;
    // sdk.ins().init();
    GameData.ins.initUserData();
    // NetManager.ins.login();
    ReportLogs.ins.initSdk();

    SocketManager.ins.initSocket();
    GameData.ins.moneyPool = new cc.NodePool("moneyPrefab");

    // 监听房间数据变化
    this.node.on("onRoomDataChange", () => {
      this.drawRankUi();
      // 更新页码显示
      const curPage = Number(GameData.ins.pageInfo.page) || 1;
      const allPages = Math.ceil(GameData.ins.pageInfo.total / Number(GameData.ins.pageInfo.pageSize));
      this.pageNum.string = `第${curPage}/${allPages}页`;
    })

    this.node.on("onJoinRoom", () => {
      GameData.ins.model = 2;
      this.toggleNodeVisibility(this.startNode, false);
      this.toggleNodeVisibility(this.readyNode, true);
    })

    this.node.on("onLeaveRoom", () => {
      GameData.ins.model = 1;
      this.toggleNodeVisibility(this.startNode, true);
      this.toggleNodeVisibility(this.readyNode, false);
      console.log("离开房间");
      //上报日志
      ReportLogs.ins.behaviorReporting("房间操作", "离开房间", GameData.ins.gameState.roomId);
    })

    this.node.on("downTime", () => {
      this.timeTxt.string = `${GameData.ins.downTime}秒`;
    })

    this.node.on("rdDownTime", () => {
      if (GameData.ins.rdDownTime >= 1) {
        this.rdDownTxt.string = `${GameData.ins.rdDownTime}`;
        GameData.ins.model = 2;
        GameData.ins.list = [];
        this.toggleNodeVisibility(this.startNode, false);
        this.toggleNodeVisibility(this.endNode, false);
        this.toggleNodeVisibility(this.readyNode, false);
        this.toggleNodeVisibility(this.rdNode, true);

        GameData.ins.getMoney = 0;
        GameData.ins.downTime = 20;
        this.timeTxt.string = `${GameData.ins.downTime}秒`;
        this.moneyTxt.string = `￥${GameData.ins.getMoney}`;
        GameData.ins.isOver = false;

        if (GameData.ins.rdDownTime === 1) {
          this.scheduleOnce(() => {
            this.moveNode.on(cc.Node.EventType.TOUCH_START, this.onMouseDown, this);
            this.toggleNodeVisibility(this.rdNode, false);
            GameData.ins.mainNode.emit("gameStart");
          }, 1);
        }
      }
    })

    this.node.on("gameDataUpdate", () => {
      // this.drawListUi();
      this.moneyTxt.string = `￥${GameData.ins.getMoney}`;

    })

    this.node.on("gameEnd", () => {
      clearInterval(this.jsTime);
      this.jsNode.active = false;
      this.jsTxt.string = "3";
      this.moveNode.off(cc.Node.EventType.TOUCH_START);
      // this.startNode.active = true;
      this.endMoneyTxt.string = `￥${GameData.ins.getMoney}`;
      this.toggleNodeVisibility(this.readyNode, true);
      this.toggleNodeVisibility(this.listNode, false);
      //上报日志
      ReportLogs.ins.behaviorReporting("房间操作", "游戏结束", GameData.ins.gameState.roomId);
    })

    this.node.on("gameStart", () => {
      this.moveNode.on(cc.Node.EventType.TOUCH_START, this.onMouseDown, this);
      this.toggleNodeVisibility(this.rdNode, false);
      //上报日志
      ReportLogs.ins.behaviorReporting("房间操作", "游戏开始", GameData.ins.gameState.roomId);
    })

    this.node.on("onTip", (str) => {
      this.onTipUi(str);
    });

    if (GameData.ins.searchRoomId) {
      this.scheduleOnce(() => {
        this.inputRoomId.string = GameData.ins.searchRoomId;
        this.joinRoom();
      }, 0.1)
    }

    this.node.on("gameJs", () => {
      this.jsNode.active = true;
      this.startJsTimer();
    })


    window["windowOnStart"] = (res) => {
      console.log("windowOnStart")
      if (this.checkNetworkConnection()) {
        SocketManager.ins.socket.emit('startGame', {
          roomId: GameData.ins.roomId,
          userId: GameData.ins.username,
        })
      }
    }
    window["windowOnUp"] = (res) => {
      console.log("windowOnUp")
      const node = this.createMoneyNode();
      node.setPosition(0, 700);
      this.aniNode.addChild(node);

      if (this.checkNetworkConnection()) {
        SocketManager.ins.socket.emit('updateScore', {
          roomId: GameData.ins.roomId,
          userId: GameData.ins.username,
        })
      }
    }
    window["windowOnJoin"] = (res) => {
      // GameData.ins.mainNode.emit("windowOnJoin", res);
      console.log(res);
      GameData.ins.username = res.username;
      GameData.ins.nickName = res.username;
      GameData.ins.avatar = "http://m.heitu.com/Static/Default/Home/images/bg_touxiang_wutouxiang.png";
      this.joinRoom();
    }
    window['windowOnCreateRoom'] = (res) => {
      console.log(res);
      GameData.ins.username = res.username;
      GameData.ins.nickName = res.username;
      GameData.ins.avatar = "http://m.heitu.com/Static/Default/Home/images/bg_touxiang_wutouxiang.png";
      this.onCreateRoom();
    }

    window['windowOnInputRoom'] = (res) => {
      this.inputRoomId.string = res.roomId + "";
    }

    window['windowExitRoom'] = (res) => {
      this.onLeave();
    }

    window['windowDismiss'] = (res) => {
      this.onDismiss();
    }

    window['windowGetRoomId'] = (res) => {
      return GameData.ins.roomId;
    }

    // 添加网络状态监听
    this.setupNetworkListeners();
  }

  /**
   * 设置网络状态监听
   */
  private setupNetworkListeners() {
    // 断开连接
    this.node.on("disconnect", () => {
      this.showReconnectTip("网络已断开，正在重连...");
      this.startReconnectCountdown();
    });

    // 重连中
    this.node.on("reconnecting", () => {
      this.reconnectCount++;
      this.showReconnectTip(`正在进行第 ${this.reconnectCount} 次重连...`);
    });

    // 重连成功
    this.node.on("reconnect", () => {
      this.hideReconnectTip();
      this.onTipUi("网络已重新连接");
      this.reconnectCount = 0;
      this.isReconnecting = false;

      // 如果在房间中，重新加入房间
      if (GameData.ins.gameState.roomId) {
        this.rejoinRoom();
      }
    });

    // 重连失败
    this.node.on("reconnect_failed", () => {
      if (this.reconnectCount >= this.MAX_RECONNECT_COUNT) {
        this.showReconnectTip("重连失败，请检查网络后重试");
        this.isReconnecting = false;
        // 返回单机模式
        this.backToSingleMode();
      }
    });
  }

  /**
   * 显示重连提示
   */
  private showReconnectTip(message: string) {
    this.onTipUi(message);
  }

  /**
   * 隐藏重连提示
   */
  private hideReconnectTip() {
    // 不需要特别处理，因为onTipUi会自动隐藏
  }

  /**
   * 开始重连倒计时
   */
  private startReconnectCountdown() {
    if (this.isReconnecting) return;
    this.isReconnecting = true;
    this.reconnectCount = 0;

    // 暂停游戏相关操作
    this.pauseGame();
  }

  /**
   * 重新加入房间
   */
  private async rejoinRoom() {
    if (!this.checkNetworkConnection()) return;

    try {
      const response = await new Promise((resolve, reject) => {
        const timeout = setTimeout(() => reject(new Error('Timeout')), 5000);
        //上报日志
        ReportLogs.ins.behaviorReporting("房间操作", "重连后，重新进入房间操作", GameData.ins.gameState.roomId);

        SocketManager.ins.socket.emit('join-room', {
          roomId: GameData.ins.gameState.roomId,
          userId: GameData.ins.username,
          avatar: GameData.ins.avatar,
          nickName: GameData.ins.nickName,
        }, (response) => {
          clearTimeout(timeout);
          resolve(response);
        });
      });

      // 处理重连成功
      this.resumeGame();
    } catch (error) {
      // 处理重连失败
      this.backToSingleMode();
    }
  }

  /**
   * 返回单机模式
   */
  private backToSingleMode() {
    GameData.ins.model = 1;
    GameData.ins.roomId = null;
    GameData.ins.list = [];
    GameData.ins.roomOwnerId = null;

    // 显示开始界面
    this.startNode.active = true;
    this.readyNode.active = false;
    this.endNode.active = false;
    this.rdNode.active = false;

    this.onTipUi("已切换至单机模式");
  }

  /**
   * 暂停游戏
   */
  private pauseGame() {
    // 暂停触摸事件
    this.moveNode.off(cc.Node.EventType.TOUCH_START, this.onMouseDown, this);

    // 暂停倒计时
    this.unschedule(this.drawDownTimeTxt);

    // 如果在游戏中，保存当前状态
    if (GameData.ins.model === 2 && !GameData.ins.isOver) {
      GameData.ins.isOver = true;
    }
  }

  /**
   * 恢复游戏
   */
  private resumeGame() {
    if (GameData.ins.model === 2 && !GameData.ins.isOver2) {
      // 重新绑定触摸事件
      this.moveNode.on(cc.Node.EventType.TOUCH_START, this.onMouseDown, this);

      // 恢复倒计时
      if (GameData.ins.downTime > 0) {
        this.schedule(this.drawDownTimeTxt, 1);
      }

      GameData.ins.isOver = false;
    }
  }

  /**
   * 检查网络连接状态
   */
  private checkNetworkConnection(): boolean {
    if (!SocketManager.ins.socket?.connected) {
      if (!this.isReconnecting) {
        this.showReconnectTip("网络未连接，正在重连...");
        this.startReconnectCountdown();
      }
      return false;
    }
    return true;
  }

  /**
   * 加入房间
   */
  public async joinRoom() {
    let roomId = this.inputRoomId.string;
    if (!Number(roomId)) {
      this.onTipUi("请输入房间号");
      return;
    }

    //上报日志
    ReportLogs.ins.behaviorReporting("房间操作", "点击进入房间按钮", roomId);

    await SocketManager.ins.socket.emit('join-room', {
      roomId: roomId,
      userId: GameData.ins.username,
      avatar: GameData.ins.avatar,
      nickName: GameData.ins.nickName,
    });
  }

  public onTipUi(str) {
    this.tipNode.stopAllActions();
    this.tipNode.active = true;
    this.tipNode.opacity = 255;
    this.tipNode.getComponent(cc.Label).string = str;
    this.tipNode.y = 0;
    cc.tween(this.tipNode)
      .to(1, { y: 300 })
      .call(() => {
        this.tipNode.active = false;
      })
      .start();
  }

  /**
   * 单机模式 开始游戏
   */
  public onStart() {
    GameData.ins.model = 1;
    this.moveNode.on(cc.Node.EventType.TOUCH_START, this.onMouseDown, this);
    this.schedule(this.drawDownTimeTxt, 1);
    this.startNode.active = false;
    this.endNode.active = false;
    GameData.ins.getMoney = 0;
    GameData.ins.downTime = 20;
    this.timeTxt.string = `${GameData.ins.downTime}秒`;
    this.moneyTxt.string = `￥${GameData.ins.getMoney}`;
    GameData.ins.isOver = false;
  }

  /**
   * 联机模式 创建房间
   */
  async onCreateRoom() {
    if (!this.checkNetworkConnection()) return;

    await SocketManager.ins.socket.emit('create-room', {
      userId: GameData.ins.username,
      avatar: GameData.ins.avatar,
      nickName: GameData.ins.nickName
    });

  }

  /**
   * 绘制排行列表
   */
  public drawListUi() {
    let that = this;
    let list = objSort("money", GameData.ins.list);
    let res = null;
    list.forEach((ele, i) => {
      ele.rank = i + 1;
      if (ele.roleId == GameData.ins.roleId) {
        res = ele;
      }
    })
    drawScroll(that.listCont, list, that.itemPrefab2, "ItemEle", 1, 0, 15);
  }

  /**
   * 绘制加入列表
   */
  public drawRankUi() {
    let that = this;
    let list = objSort("score", GameData.ins.gameState.players);
    let arr = [];

    for (let i: number = 0; i < list.length; i++) {
      if (list[i] && !list[i].isExit) {
        arr.push(list[i]);
      }
    }

    arr.forEach((ele, i) => {
      ele.rank = i + 1;
      // if (ele.roomRoot) {
      //   //标记房主
      //   GameData.ins.roomOwnerId = ele.userId;
      // }
    })

    this.myRankTxt.string = "我的排名: " + (GameData.ins.myInfo.rank || 0);

    this.myScoreTxt.string = "我的积分: " + (GameData.ins.myInfo.score || 0);

    this.allNum.string = "房间人数: " + GameData.ins.pageInfo.total;

    drawScroll(that.readyCont, arr, that.itemPrefab, "ItemEle", 1, 0, 15);
    this.roomIdTxt.string = `${GameData.ins.gameState.roomId}`;
    if (GameData.ins.isRoomOwner) {
      this.startBtn.active = true;
      this.disBtn.active = true;
      this.readyBtn.active = false;
      this.leaveBtn.active = false;
      this.shareBtn.active = true;
    } else {
      this.startBtn.active = false;
      this.disBtn.active = false;
      this.shareBtn.active = false;
      this.readyBtn.active = false;
      this.leaveBtn.active = true;
    }
  }


  /**
   * 准备 开始
   */
  public onReady(e, key) {
    if (!this.checkNetworkConnection()) return;

    switch (key) {
      case "2":
        console.log(GameData.ins.username);
        //上报日志
        ReportLogs.ins.behaviorReporting("房间操作", "房主开始游戏", GameData.ins.gameState.roomId);
        SocketManager.ins.socket.emit('start-game', {
          roomId: GameData.ins.gameState.roomId,
          userId: GameData.ins.username,
        });
        break;
    }
  }

  /**
   * 退出
   */
  public onLeave() {
    if (!this.checkNetworkConnection()) return;

    console.log("onLeave");
    GameData.ins.list = [];
    SocketManager.ins.socket.emit('leave-room', {
      roomId: GameData.ins.gameState.roomId,
      userId: GameData.ins.username
    });
    GameData.ins.mainNode.emit("onLeaveRoom");
  }

  /**
   * 解散
   */
  public onDismiss() {
    if (!this.checkNetworkConnection()) return;

    GameData.ins.gameState.players = [];
    SocketManager.ins.socket.emit('dismiss-room', {
      roomId: GameData.ins.gameState.roomId,
      userId: GameData.ins.username
    });

    GameData.ins.gameState.ownerId = null;
    GameData.ins.gameState.players = [];
    GameData.ins.gameState.roomId = null;
    GameData.ins.mainNode.emit("onLeaveRoom");
  }

  public onShare() {
    this.roomIdTxt2.string = `${GameData.ins.gameState.roomId}`;
    this.shareNode.active = !this.shareNode.active;
    if (this.shareNode.active) {
      //@ts-ignore
      window.appendIndexImg();
    } else {
      //@ts-ignore
      window.removeIndexImg();
    }
  }

  /**
   * 点击分页
   * @param e 
   * @param key 
   */
  onPageClick(e: cc.Event, key) {
    const curPage = Number(GameData.ins.pageInfo.page) || 1;
    const allPages = Math.ceil(GameData.ins.pageInfo.total / Number(GameData.ins.pageInfo.pageSize));
    let page = curPage + (Number(key) === 1 ? -1 : Number(key) === 2 ? 1 : 0);
    page = Math.max(1, Math.min(page, allPages));
    GameData.ins.pageInfo.page = page;
    // this.pageNum.string = `第${page}/${allPages}页`;
    // 获取房间用户数据
    GameData.ins.getRoomUserData(page, Number(GameData.ins.pageInfo.pageSize), GameData.ins.isOver2 ? "score" : "lastActive", GameData.ins.isOver2 ? "desc" : "asc", GameData.ins.username);
  }

  /**
   * 倒计时
   */
  drawDownTimeTxt() {
    GameData.ins.downTime--;
    this.timeTxt.string = `${GameData.ins.downTime}秒`;
    if (GameData.ins.downTime <= 0) {
      GameData.ins.isOver = true;
      let that = this;
      this.unschedule(that.drawDownTimeTxt);
      this.moveNode.off(cc.Node.EventType.TOUCH_START);
      // this.startNode.active = true;
      this.endMoneyTxt.string = `￥${GameData.ins.getMoney}`;
      this.endNode.active = true;
    }
  }

  onMouseDown(e) {

    if (GameData.ins.isOver) return;

    e.currentTarget.on(cc.Node.EventType.TOUCH_MOVE, this.onMouseMove, this);

    e.currentTarget.on(cc.Node.EventType.TOUCH_CANCEL, this.onMouseUp, this)

    e.currentTarget.on(cc.Node.EventType.TOUCH_END, this.onMouseUp, this)

  }

  onMouseMove(e) {

    let delta = e.getDelta();

    if (delta) {

      this.moveNode.y += delta.y;
    }

    if (this.moveNode.y > 240) {

      this.moveNode.y = 240;
    }

    if (this.moveNode.y < -320) {

      this.moveNode.y = -320;
    }
  }

  /**
   * 
   */
  onMouseUp(e) {
    this.clearTouchEvents(e.currentTarget);

    if (this.moveNode.y > -100) {
      const node = this.createMoneyNode();
      node.setPosition(0, 700);
      this.aniNode.addChild(node);

      // 添加动画完成后的回收
      const anim = node.getComponent(cc.Animation);
      if (anim) {
        anim.on('finished', () => {
          this.recycleMoneyNode(node);
        }, this);
      } else {
        // 如果没有动画，设置一个延时回收
        this.scheduleOnce(() => {
          this.recycleMoneyNode(node);
        }, 2);
      }

      this.moveNode.y = -320;

      if (GameData.ins.model == 2 && !GameData.ins.isOver) {
        if (this.checkNetworkConnection()) {
          GameData.ins.getMoney += 100
          GameData.ins.mainNode.emit("gameDataUpdate");
        }
      }
    } else {
      this.moveNode.y = -320;
    }
  }

  private clearTouchEvents(target: cc.Node) {
    target.off(cc.Node.EventType.TOUCH_MOVE, this.onMouseMove, this);
    target.off(cc.Node.EventType.TOUCH_CANCEL, this.onMouseUp, this);
    target.off(cc.Node.EventType.TOUCH_END, this.onMouseUp, this);
  }

  private clearAllEvents() {
    // 清理所有事件监听
    this.moveNode?.off(cc.Node.EventType.TOUCH_START, this.onMouseDown, this);
    this.moveNode?.off(cc.Node.EventType.TOUCH_MOVE, this.onMouseMove, this);
    this.moveNode?.off(cc.Node.EventType.TOUCH_CANCEL, this.onMouseUp, this);
    this.moveNode?.off(cc.Node.EventType.TOUCH_END, this.onMouseUp, this);
  }

  private clearAllTimers() {
    // 清理所有定时器
    if (this.jsTime) {
      clearInterval(this.jsTime);
      this.jsTime = null;
    }
    this.unscheduleAllCallbacks();
  }

  onDestroy() {
    this.clearAllEvents();
    this.clearAllTimers();
    this.clearNodePool();

    // 清理全局事件监听
    this.clearGlobalEventListeners();
  }

  private clearGlobalEventListeners() {
    const events = [
      "onRoomDataChange",
      "onJoinRoom",
      "onLeaveRoom",
      "downTime",
      "rdDownTime",
      "gameDataUpdate",
      "gameEnd",
      "gameStart",
      "onTip",
      "gameJs",
      "disconnect",
      "reconnecting",
      "reconnect",
      "reconnect_failed"
    ];
    events.forEach(event => this.node.off(event));
  }

  private clearNodePool() {
    if (GameData.ins.moneyPool) {
      GameData.ins.moneyPool.clear();
    }
  }

  // 优化金币节点的创建和回收
  private createMoneyNode(): cc.Node {
    let node = GameData.ins.moneyPool.get();
    if (!node) {
      node = cc.instantiate(this.moneyPrefab);
    }
    return node;
  }

  private recycleMoneyNode(node: cc.Node) {
    if (node && node.isValid) {
      GameData.ins.moneyPool.put(node);
    }
  }

  // 优化定时器使用
  private startJsTimer() {
    this.clearJsTimer();
    this.jsNum = 3;
    this.jsTxt.string = `${this.jsNum}`;

    this.jsTime = setInterval(() => {
      this.jsNum -= 1;
      this.jsTxt.string = `${this.jsNum}`;

      if (Number(this.jsNum) <= 0) {
        this.clearJsTimer();

        if (!GameData.ins.isOver2) {
          GameData.ins.isOver2 = true;
          GameData.ins.mainNode.emit("gameEnd");
          GameData.ins.pageInfo.page = 1;
          GameData.ins.getRoomUserData(GameData.ins.pageInfo.page, Number(GameData.ins.pageInfo.pageSize), "score", "desc", GameData.ins.username);
          // GameData.ins.mainNode.emit("onRoomDataChange");
        }
      }
    }, 1000);
  }

  private clearJsTimer() {
    if (this.jsTime) {
      clearInterval(this.jsTime);
      this.jsTime = null;
    }
  }

  private toggleNodeVisibility(node: cc.Node, isVisible: boolean) {
    node.active = isVisible;
  }
}